﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class waitingRoomScript : MonoBehaviour {
	
	public roomPlaneScript[] planes;
	private NetworkScript network;
	private DataScript data;
	private List<PlayerObject> players;
	int playerAmount = 0;
	
	// Use this for initialization
	void Start () {
		//chat = new chatSystem(networkView);
		data = GameObject.FindGameObjectWithTag("DataManager").GetComponent<DataScript>();
		network = GameObject.FindGameObjectWithTag("NetworkManager").GetComponent<NetworkScript>();
		players = new List<PlayerObject>();
	}
	
	// Update is called once per frame
	void Update () {
		if(Input.GetKeyDown(KeyCode.Space))
		{
			network.loadLevel(1);
		}
	}
	
	void OnServerInitialized()
	{
		networkView.RPC("Entered", RPCMode.AllBuffered,Network.player.guid,data.playerName);
	}
	
	void OnConnectedToServer()
	{
		networkView.RPC("Entered", RPCMode.AllBuffered,Network.player.guid,data.playerName);
	}
	
	void OnPlayerDisconnected(NetworkPlayer player)
	{
		networkView.RPC("Exited", RPCMode.AllBuffered,player.guid);
	}
	
	void refreshPlayer(List<PlayerObject> playerList)
	{
        for(int i = 0; i < 6; i++) {
			if(i < playerList.Count)
			{
				planes[i].updatePlane(playerList[i].name);
			}
			else
			{
				planes[i].updatePlane(false);
			}
        }
	}
	
	[RPC]
	void Entered(string id, string name)
	{
		players.Add(new PlayerObject(id,name));
		playerAmount ++;
		refreshPlayer(players);
	}
	
	[RPC] 
	void Exited(string id)
	{
		PlayerObject disconnectedPlayer = null;
		for(int i = 0; i < players.Count; i++)
		{
			if(id == players[i].id)
			{
				disconnectedPlayer = players[i];
				break;
			}
		}
		if(disconnectedPlayer != null)
		{
			players.Remove(disconnectedPlayer);
			playerAmount --;
			refreshPlayer(players);
		}
	}
}
